$(function () {
  // CHAT.init();
  //滚动条
  $(".chatList_scroll").yi_scroll();
  //聊天 打开弹窗
  $('body').on('click', '.chat-trigger', function (event) {
    event.preventDefault();
    $('.chat-pop').addClass('is-visible3');
    chatTrigger=true;
    friendid = $(this).attr('friendid');
    apkAlarmid = $(this).attr('alarmid');

    var obj = {
      "type": 2,
      "chatRecord": {
        "id": null,
        "userid": chatId,
        "friendid": friendid,
        "message": null,
        "ext": "",
        "alarmid":apkAlarmid
      }
    };
    // CHAT.chat(JSON.stringify(obj));
    chatSend.send(JSON.stringify(obj));
    loadChatSnapshot(apkAlarmid);
    newAlarmFn();
  });
  //聊天 关闭窗口
  $('.chat-pop').on('click', function (event) {
    if (
      $(event.target).is('.cd-popup-close') ||
      $(event.target).is('.chat-pop')
    ) {
      event.preventDefault();
      $(this).removeClass('is-visible3');
      chatTrigger = false;
      $('#chatModal input').val('');
    }
  });
  // 发送消息
  $('#chatSendBtn').on('click', function () {
    var text = $('#chatModal .chat_operation textarea').val();
    if (!text) {
      tipModalFunc('内容不能为空！');
      return;
    }
    var obj = {
      "type": 1,
      "chatRecord": {
        "id": null,
        "userid": chatId,
        "friendid": friendid,
        "message": text,
        "ext": "",
        "alarmid":apkAlarmid
      }
    };
    chatSend.send(JSON.stringify(obj));

    // 重新加载好友快照
    setTimeout(function(){
      loadChatSnapshot();
    },500);
    

  });




});

var webhost = location.hostname.toLowerCase();
// 应答盒的报警语音
var chatId = localStorage.getItem('userOrgId');
// chatId = 1; //测试
// console.log('ws://' + webhost + ':9091/websocket/manual/' + chatId);
// // const respondVioceWs = new Sockette('ws://' + webhost + ':9091/websocket/manual/' + chatId, {
// const respondVioceWs = new Sockette('ws://' + webhost + ':9091/websocket/manual/' + chatId, {
//   timeout: 5e3,
//   maxAttempts: 10,
//   onopen: function (e) {
//     console.log(e)
//     // var message = {
//     //   "type": 0,
//     //   "chatRecord": {
//     //     "id": null,
//     //     "userid": 1,
//     //     "friendid": "",
//     //     "message": "",
//     //     "ext": "",
//     //     "alarmid":''
//     //   }
//     // };
//     // respondVioceWs.send(JSON.stringify(message));
//   },
//   onmessage: function (e) {

//     console.log(e);
//     var data = e.data;
//     data = $.parseJSON(data);
//     console.log(data);
//     // 刷新报警列表
//     newAlarmFn();
//     // var str = e.data;
//     // var strs = str.split(",");
//     // var cmd = strs[0];
//     // //接收到报警信息
//     // console.log(str)


//   },
//   onreconnect: e => console.log('Reconnecting...', e),
//   onmaximum: e => console.log('Stop Attempting!', e),
//   onclose: e => console.log('Closed!', e),
//   onerror: e => console.log('Error:', e)
// });

// 聊天信息
const chatSend = new Sockette('ws://' + webhost + ':9001/ws', {
  timeout: 5e3,
  maxAttempts: 10,
  onopen: function (e) {
    var message = {
      "type": 0,
      "chatRecord": {
        "id": null,
        "userid": chatId,
        "friendid": null,
        "message": null,
        "ext": null,
        "alarmid":null
      }
    };
    chatSend.send(JSON.stringify(message));
    
    // 重新加载好友快照
    setTimeout(function(){
      loadChatSnapshot();
    },500);
    
  },
  onmessage: function (e) {

    console.log(e);
    var data = e.data;
    data = $.parseJSON(data);
    console.log(data);


    // 重新加载好友快照
    loadChatSnapshot();
    // 如果当前页面在聊天窗口，发送type=2的聊天信息，将信息设置为已读
    if(chatTrigger){
      var obj = {
        "type": 2,
        "chatRecord": {
          "id": null,
          "userid": chatId,
          "friendid": friendid,
          "message": null,
          "ext": "",
          "alarmid":null
        }
      };
      // CHAT.chat(JSON.stringify(obj));
      chatSend.send(JSON.stringify(obj));
    }
  },
  onreconnect: e => console.log('Reconnecting...', e),
  onmaximum: e => console.log('Stop Attempting!', e),
  onclose: e => console.log('Closed!', e),
  onerror: e => console.log('Error:', e)
});



window.util = {
  getMessage: function (type, userid, friendid, msg, msgid, ext,apkAlarmid) {
    return {
      type: type,
      chatRecord: {
        id: msgid,
        userid: userid,
        friendid: friendid,
        message: msg,
        ext: ext,
        alarmid:apkAlarmid
      }
    };
  },
}
var loadChatSnapshotArr = [];
// 展示聊天快照
function loadChatSnapshot() {
  // 加载未读的聊天记录
  $.ajax({
    url: "/chatRecord/findByUserIdAndFriendId?userid=" + chatId + "&friendid=" + friendid + "&alarmid=" + apkAlarmid,
    success: function (data) {
      if(data.status==200){
        var data = data.data;
        loadChatSnapshotArr = data;
        console.log(data);
        $('#chatModal .chat_operation textarea').val('');
        $("#chatModal .modalContentList").html('');
        for (var i = 0; i < data.length; i++) {
          var item = data[i];
          if (item.userid == chatId) {
            if (item.message) {
              $("#chatModal .modalContentList").append(`
              <div class="me_lists">
              <div class="header_img">
                <img src="image/default_user_pic.png" width="40px" height="40px">
              </div>
              <div class="msg-wrapper left">
                <p class="msg-right-green">` + item.message + `</p>
              </div>
            </div>`);
            }
            if (item.ext) {
              $("#chatModal .modalContentList").append(`
              <div class="me_lists">
              <div class="header_img">
                <img src="image/default_user_pic.png" width="40px" height="40px">
              </div>
              <div class="msg-wrapper left">
                <p class="msg-right-green vioceImg" index="` + i + `">` + '语音' + `</p>
              </div>
            </div>`);
            }
  
          } else {
            if (item.message) {
              $("#chatModal .modalContentList").append(`
                <div class="friend_lists">
                <div class="header_img">
                  <img src="image/default_user_pic.png" width="40px" height="40px">
                </div>
                <div class="msg-wrapper right">
                  <p class="msg-left-white">` + item.message + `</p>
                </div>
              </div>`);
            }
            if (item.ext) {
              $("#chatModal .modalContentList").append(`
                <div class="friend_lists">
                <div class="header_img">
                  <img src="image/default_user_pic.png" width="40px" height="40px">
                </div>
                <div class="msg-wrapper right">
                  <p class="msg-left-white vioceImg vioceImg_black" index="` + i + `">` + '语音' + `</p>
                </div>
              </div>`);
            }
          }
        }
        var height = $("#chatModal .modalContentList").height();
        console.log(height)
        // 默认在最底部
        $("#chatModal .modalContentList").css('top', -height + 'px');
      }

    }
  });


}